<template>
  <div v-if='actionPlantype == "1" || (actionPlantype == null && plantype == "1")'>
    <el-tabs type="border-card" v-model="selectedTab" @tab-click="onChnageTab">
      <el-tab-pane label="销售业绩" name="3">
        <div>
          <h4>销售业绩规则设置</h4>
          <h5>提成计算方式</h5>
          <p>
            阶梯式计算：设置后呈阶梯式增长，按员工个人当月销售业绩计算提成
            <br/>例1：当月业绩为1-10000元（含1元）时2%，10000-15000元（含10000元）时6%，员工业绩13000元，提成为：13000*6%
            <br/>例2：当月业绩为1-1000元（含1元）时提成金额为0元，1000-1500元（含1000元）时提成金额为100元，员工业绩1300元，提成为：100元；
          </p>
          <div>
            <h5 style="display:inline-block">提成产品</h5>
            <p>所有商品、服务、次卡的售卖</p>
<!--            <el-button type="primary" size="small" @click='selectProduct' style='margin-left: 20px'-->
<!--                       icon='el-icon-setting'>设置-->
<!--            </el-button>-->
<!--            <span class='hasTips' v-if='activeProductList.length > 0'>-->
<!--              已添加：-->
<!--              <el-tag type="success" v-for='(item, index) in activeProductList' :key='index'-->
<!--                      style='margin-right: 20px;'>{{productList[item]}}</el-tag>-->
<!--            </span>-->
          </div>
        </div>
        <div class='section-edit-btns'>
          <h5 style="display:inline-block">设置区间</h5>
          <span class='tips'>*小贴士：区间最小值建议设置为1，区间最大值建议设置超出员工预期的业绩；区间必须连续（例如1-1000、1000-2000...）</span>
          <div style='margin-top: 20px'>
            <el-button v-if='!sectionEdit' type="primary" size='small' @click="openEdit" icon="el-icon-edit">编辑
            </el-button>
            <template v-else>
              <el-button type="primary" size="small" @click="onSaveCommissionSection">保 存
              </el-button>
              <el-button size="small" @click="onCancelCommissionSection">取 消</el-button>
            </template>
          </div>
        </div>
        <el-table :data="sectionData" border style="width: 60%">
          <el-table-column type='index' label='序号' align='center' width='55'></el-table-column>
          <el-table-column prop="section" label="业绩区间" width="240" align='center'>
            <template slot-scope="scope">
              <span v-if="scope.row.show">
                <el-input class="input"
                          v-model="scope.row.amountMin"
                          size="small"
                          style="width: 100px"
                          @keyup.native="scope.row.amountMin = util.replaceNumber(scope.row.amountMin)"
                          :maxlength="8"
                ></el-input>-
                <el-input
                  class="input"
                  v-model="scope.row.amountMax"
                  size="small"
                  style="width: 100px"
                  @keyup.native="scope.row.amountMax = util.replaceNumber(scope.row.amountMax)"
                  :maxlength="9"
                ></el-input>
              </span>
              <span v-else>{{scope.row.amountMin}} - {{scope.row.amountMax}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="提成方式" width="180" align='center'>
            <template slot-scope="scope">
              <el-select v-model="scope.row.commissionWay" size="small" v-if="scope.row.show==true">
                <el-option label="比例提成" :value="0"></el-option>
                <el-option label="固定提成" :value="1"></el-option>
              </el-select>
              <span v-if="scope.row.show==false">{{scope.row.commissionWay=='0' ? '比例提成':'固定提成'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="提成比例" align='center'>
            <template slot-scope="scope">
              <template>
                <span v-if="scope.row.show">
                <el-input
                  v-model="scope.row.commissionValue"
                  size="small"
                  style="width:80%"
                  @keyup.native="scope.row.commissionValue = util.replaceFloat(scope.row.commissionValue)"
                  :maxlength="6"
                ></el-input>
              </span>
                <span v-else>{{scope.row.commissionValue}}</span>
              </template>
              <span v-if="scope.row.commissionWay == '0'">%</span>
              <span v-else>元</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="deleRange(scope.$index)" :disabled='!sectionEdit'>删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-new-section">
          <el-button type="text" @click="onAddSection" icon="el-icon-plus" :disabled='!sectionEdit'>添加区间</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="服务劳动提成" name="4">
        <div>
          <h4>服务劳动提成规则</h4>
          <h5>提成计算方式</h5>
          <p>按服务所设置的常规计件提成方式计算提成</p>
          <p class='from-filter'>
            <label for>是否提成：</label>
            <el-select v-model="addGoodsForm.isCommission" placeholder="请选择" size="small">
              <el-option
                v-for="(item,index) in commissionOption"
                :label="item.label"
                :value="item.value"
                :key="index"
              ></el-option>
            </el-select>
            <el-input v-model="addGoodsForm.keyWords" placeholder="请输入服务名称" size="small"
                      style='width: 200px'></el-input>
            <el-button type="primary" size="small" icon="el-icon-search" plain @click='getPersonAchievement()'>查询
            </el-button>
            <br>
          </p>
          <p style='margin-top: 20px'>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="onChangeServiceComm(1, 4)"
            >批量修改
            </el-button>
          </p>
        </div>
        <el-table
          ref="multipleTable"
          :data="serviceList"
          tooltip-effect="dark"
          @selection-change="onSelectionChange"
          :header-cell-style='{background:"rgb(245,247,250)"}'
          key='serviceTable'
        >
          <el-table-column type="selection" width="55" align='center'></el-table-column>
          <el-table-column type="index" label="序号" width="55" align='center'></el-table-column>
          <el-table-column prop="goodsName" label="服务名称" width="120" align='center'></el-table-column>
          <el-table-column prop="goodsSalePrice" label="销售价" width="120" align='center'></el-table-column>
          <el-table-column prop="goodsMemberPrice" label="会员价" align='center'></el-table-column>
          <el-table-column prop="isCommission" label="是否提成" :formatter='formatIsCommission'
                           align='center'></el-table-column>
          <el-table-column prop='commissionWay' label="提成方式" :formatter="commissionTypeFormat" align='center'></el-table-column>
          <el-table-column prop="commissionValue" label="提成比例" align='center' :formatter='formatCommissionValue'></el-table-column>
          <el-table-column prop="address" label="操作" align='center'>
            <template slot-scope='scope'>
              <el-button type="text" @click="onChangeServiceComm(0, 4, scope.row.goodsId, scope.row.id)">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange($event, 2)"
                       @current-change="handleCurrentChange($event, 2)"
                       :current-page="pageNum"
                       :page-sizes="[5, 10, 20, 50]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total" key='2'>
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane label="活动期商品提成" name="5">
        <div class="active-commission">
          <h4>活动期商品提成规则</h4>
          <h5>提成计算方式</h5>
          <p>按商品所设置的活动期计件提成方式计算提成</p>
          <div class="p-tip">
            <h5 style="display:inline-block">活动期商品提成列表</h5>
            <span>注：活动期该商品的售卖按活动提成算，其他非活动期按销售业绩阶梯提成算</span>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-plus"
              @click="addGoodsBtn"
            >添加商品
            </el-button>
          </div>
          <p class='from-filter'>
            <label for>商品品类:</label>
            <el-cascader
              size="small"
              props.checkStrictly
              props.expandTrigger="hover"
              :options="commodityCategoryList"
              v-model="addGoodsForm.commodityCategory"
              :show-all-levels="false" style='width: 150px'
            ></el-cascader>
            <label for>商品品牌:</label>
            <el-select
              v-model="addGoodsForm.commodityBrand"
              placeholder="请选择"
              size="small" style='width: 150px'
            >
              <el-option
                v-for="(item,key) in commodityBrandList"
                :label="item.name"
                :value="item.id"
                :key="key"
              ></el-option>
            </el-select>
            <el-input
              v-model="addGoodsForm.keyWords"
              placeholder="请输入商品名称"
              size="small"
              style="width:190px" @keyup.enter.native='getActiveGoodsList'
            ></el-input>
            <el-button type="primary" size="small" plain icon="el-icon-search" @click='getActiveGoodsList'>查询
            </el-button>
          </p>
          <p style='margin-top: 20px'>
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="onChangeServiceComm(1, 5)"
            >批量修改
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="delActivityCommission(0)"
            >批量删除
            </el-button>
          </p>
        </div>
        <el-table
          ref="multipleTable"
          :data="activeGoodsList"
          tooltip-effect="dark"
          @selection-change="onSelectionActiveChange"
          stripe :header-cell-style='{background:"rgb(245,247,250)"}'>
          <el-table-column type="selection" width="55" align='center'></el-table-column>
          <el-table-column type="index" label="序号" width="55" align='center'></el-table-column>
          <el-table-column prop="name" label="商品名称" width="120" align='center'></el-table-column>
          <el-table-column prop="brand" label="品牌" width="120" align='center'></el-table-column>
          <el-table-column prop="primaryClassifyName" label="品类" width="120" align='center'></el-table-column>
          <el-table-column prop="goodsParameterList" label="规格型号" width="120" align='center'>
            <template slot-scope='scope'>
              <div v-for='(item, index) in scope.row.goodsParameterList' :key='index'>
                {{item.paramName}}：{{item.paramValue}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsSalePrice" label="销售价" width="120" align='center'></el-table-column>
          <el-table-column prop="goodsMemberPrice" label="会员价" align='center'></el-table-column>
          <el-table-column label="活动时间" align='center' width='160'>
            <template slot-scope='scope'>
              <span v-if='scope.row.activityStart && scope.row.activityEnd'>{{formatDate(scope.row.activityStart)}}至{{formatDate(scope.row.activityEnd)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="commissionWay" label="提成方式" :formatter='commissionTypeFormat'
                           align='center'></el-table-column>
          <el-table-column prop="commissionValue" label="提成比例" align='center' :formatter='formatCommissionValue'></el-table-column>
          <el-table-column prop="address" label="操作" align='center'>
            <template slot-scope='scope'>
              <el-button type="text" @click="onChangeServiceComm(0, 5, scope.row.goodsShopId, scope.row.id)">修改
              </el-button>
              <el-button type='text' @click="delActivityCommission(1, scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange($event, 5)"
                       @current-change="handleCurrentChange($event, 5)"
                       :current-page="pageNum"
                       :page-sizes="[5, 10, 20, 50]" :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total" key='1'>
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
    <!--------- 设置服务提成弹窗 -------------------->
    <el-dialog :title="diaLogTitle" :visible.sync="dialogFormVisible" width='600px' center>
      <el-form :model="dialogForm" label-width="120px" size="small">
        <template>
          <el-form-item label="活动时间" required v-if='commissionRake == "5"'>
            <el-date-picker v-model="dialogForm.activityTime" type="datetimerange" start-placeholder="开始时间"
                            end-placeholder="结束时间" :picker-options="pickerOptions" @change='selectedDateChange'>
            </el-date-picker>
          </el-form-item>
          <el-form-item label="是否提成" required v-else>
            <el-radio-group v-model="dialogForm.isCommission">
              <el-radio :label="0">是</el-radio>
              <el-radio :label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
        <el-form-item label="选择提成方式" required v-if='dialogForm.isCommission == "0"'>
          <el-select v-model="dialogForm.commissionType" style="width:100px">
            <el-option label="比例提成" :value="0"></el-option>
            <el-option label="固定提成" :value="1"></el-option>
          </el-select>
          <el-input v-model="dialogForm.number" style="width:100px"
                    @keyup.native="dialogForm.number = util.replaceFloat(dialogForm.number)"></el-input>
          <span v-if="dialogForm.commissionType == 0">%</span>
          <span v-else>元</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="offConfirm" size="samll">取 消</el-button>
        <el-button type="primary" @click="onConfirmSet" size="samll">确 定</el-button>
      </div>
    </el-dialog>
    <!------------ 添加商品 ------------------------>
    <el-dialog title='添加商品' :visible.sync="addGoodsDialogFormVisible"
               class="goods-add-dialog">
      <el-form :model="addGoodsForm" label-width="100px" size='small'>
        <div>
          <label>商品品类</label>
          <el-cascader
            size="small"
            props.checkStrictly
            props.expandTrigger="hover"
            :options="commodityCategoryList"
            v-model="addGoodsForm.commodityCategory"
            :show-all-levels="false"
          ></el-cascader>
          <label>商品品牌</label>
          <el-select v-model="addGoodsForm.commodityBrand" size='small'>
            <el-option
              v-for="(item,key) in commodityBrandList"
              :label="item.name"
              :value="item.id"
              :key="key"
            ></el-option>
          </el-select>
          <label>是否提成</label>
          <el-select v-model="addGoodsForm.isCommission" size='small' style='width: 120px'>
            <el-option
              v-for="(item,key) in commissionOption"
              :label="item.label"
              :value="item.value"
              :key="key"
            ></el-option>
          </el-select>
          <el-input
            v-model="addGoodsForm.keyWords"
            style='width: 190px;'
            placeholder="请输入商品名称" size='small' @keyup.enter.native='getPersonAchievement(0)'
          ></el-input>
          <el-button type="primary" icon="el-icon-search" size="small" @click='getPersonAchievement(0)' plain>查询
          </el-button>
        </div>
        <div>
          <el-button type="primary" icon="el-icon-setting" size="small" class="set-active-comm"
                     @click='onChangeActiveComm(1)'>设置活动期提成
          </el-button>
        </div>
      </el-form>
      <el-table
        ref="multipleTable"
        :data="dialogGoodsList"
        tooltip-effect="dark"
        @selection-change="onSelectionAddGoods"
        stripe :header-cell-style='{background:"rgb(245,247,250)"}'>
        <el-table-column type="selection" width="55" align='center'></el-table-column>
        <el-table-column type="index" label="序号" width="55" align='center'></el-table-column>
        <el-table-column prop="goodsName" label="商品名称" width="120" align='center'></el-table-column>
        <el-table-column prop="brand" label="品牌" width="120" align='center'></el-table-column>
        <el-table-column prop="primaryClassifyName" label="品类" width="120" align='center'></el-table-column>
        <el-table-column label="规格型号" width="120" align='center'>
          <template slot-scope='scope'>
            <div v-for='(item, index) in scope.row.goodsParameterList' :key='index'>
              {{item.paramName}}：{{item.paramValue}}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="goodsSalePrice" label="销售价" width="120" align='center'></el-table-column>
        <el-table-column prop="goodsMemberPrice" label="会员价" align='center'></el-table-column>
        <el-table-column prop="isCommission" label="是否提成" align='center' :formatter='formatIsCommission'></el-table-column>
        <el-table-column prop="commissionWay" label="提成方式" align='center'
                         :formatter='commissionTypeFormat'></el-table-column>
        <el-table-column prop="commissionValue" label="提成比例" align='center' :formatter='formatCommissionValue'></el-table-column>
        <el-table-column prop="address" label="操作" align='center'>
          <template slot-scope='scope'>
            <el-button type="text" @click="onChangeActiveComm(0, scope.row.goodsId, scope.row.id)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot='footer' class="dialog-footer" style='overflow: hidden'>
        <el-pagination @size-change="addGoodsHandleSizeChange($event, 0)"
                       @current-change="addGoodsHandleCurrentChange($event, 0)"
                       :current-page="addGoodsForm.pageNum"
                       :page-sizes="[5, 10, 20, 50]" :page-size="addGoodsForm.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="addGoodsForm.total">
        </el-pagination>
      </div>
      <!--------------设置活动期商品提成弹框----------- -->
      <el-dialog width="600px" title="设置活动期商品提成" :visible.sync="innerVisible" :show-close='false' append-to-body center>
        <el-form :model="dialogForm" label-width='120px' size='small'>
          <el-form-item label="活动时间" required>
            <el-date-picker v-model="dialogForm.activityTime" type="datetimerange" start-placeholder="开始时间"
                            end-placeholder="结束时间" :picker-options="pickerOptions" @change='selectedDateChange'>
            </el-date-picker>
          </el-form-item>
          <el-form-item label='选择提成方式' required>
            <el-select v-model='dialogForm.commissionType'>
              <el-option label='比例提成' :value='0'></el-option>
              <el-option label='固定提成' :value='1'></el-option>
            </el-select>
            <el-input v-model='dialogForm.number' style='width: 200px'
                      @keyup.native="dialogForm.number = util.replaceFloat(dialogForm.number)">
              <template slot='append'>
                <span v-if='dialogForm.commissionType == "0"'>%</span>
                <span v-else>元</span>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="offConfirm">取 消</el-button>
          <el-button type="primary" @click="onConfirmSet">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
    <!--添加产品-->
    <el-dialog width="500px" title="添加产品" :visible.sync="selectProductVisible" :show-close='false' center>
      <el-checkbox-group v-model="activeProduct" :min="1">
        <el-checkbox v-for='(item, index) in productList' :key='index' :label="index+''" class='checkbox-block'>{{item}}
        </el-checkbox>
      </el-checkbox-group>
      <p class='mark'>※未选择的产品将不计算提成</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectProduct" size='midum'>取 消</el-button>
        <el-button type="primary" @click="commissionEdit" size='midum'>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import s from '@/util/state'
  import util from '@/util'
  import {
    selectByGoodsId,
    getGoodsClassifyTreeList,
    getCommercialTenant,
    commissionDetail, // 修改提成方案
    commissionRang, //新增提成区间
    deleteCommission,
    deleRange,     // 删除提成区间
    updRange,
    activeGoodsList
  } from '@/api'
  import {mapState} from 'vuex'

  export default {
    data () {
      return {
        util: util,
        diaLogTitle: '',
        activeProduct: [0,1,2],      //添加产品
        activeProductList: [],  //已添加产品
        selectProductVisible: false,  //添加产品弹框
        innerVisible: false, // 活动商品提成修改弹框
        commissionDetailId: '', //个人提成方案详情Id
        selectedTab: '3',
        actionPlantype: this.actionPlanType,
        plantype: this.planType,
        sectionData: [],         //区间
        alreadySectionData: [],  //区间暂存
        sectionEdit: null, // 1-新增  2-编辑
        productList: ['所有商品售卖', '所有服务售卖', '所有次卡售卖'],
        commissionOption: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '是',
            value: 0
          },
          {
            label: '否',
            value: 1
          }
        ],
        serviceList: [],
        dialogFormVisible: false,
        // 设置提成弹窗
        dialogForm: {
          isCommission: 0,
          commissionType: 1,
          number: '',
          activityTime: []
        },
        commodityBrandList: [],
        commodityCategoryList: [],
        addGoodsDialogFormVisible: false,
        pageSize: 10,
        pageNum: 1,
        total: 0,
        // 添加商品弹窗
        addGoodsForm: {
          isCommission: '',
          commodityBrand: '', //品牌
          commodityCategory: [''], //分类
          pageSize: 10,
          pageNum: 1,
          total: 0,
          keyWords: '',
          activityTime: [],  //活动时间筛选
        },
        dialogGoodsList: [], // 商品列表
        selectedList: [],   //勾选列表
        activeGoodsList: [],
        ids: [],    //删除的提成区间
        planId: '',  //方案id
        commissionRake: null, //提成对象:0-商品,1-服务,2-次卡,3-销售业绩,4-服务劳动,5-活动期商品
        min: 1,
        max: 100000000,
        pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()- 8.64e7;
        }
      },
      }
    },
    watch: {
      actionPlanType (newValue, oldValue) {
        this.actionPlantype = newValue
      },
      planType (newValue, oldValue) {
        this.plantype = newValue
      },
      selectedStore (newValue, oldValue) {
        if (this.isShop == '0') {
          this.shopId = this.merchantId
        } else {
          this.shopId = newValue
        }
      },
    },
    computed: mapState(['merchantId', 'power', 'businessScope', 'isShop', 'soUrce']),
    props: ['actionPlanType', 'planType', 'selectedStore',],
    mounted () {
      //判断是否门店
      if (this.isShop == '0') {
        this.shopId = this.merchantId
      } else {
        this.shopId = this.selectedStore
      }
    },
    methods: {
      commissionTypeFormat (row, column, cellValue, index) {
        if (row.commissionValue == '' || +row.commissionValue === 0) {
            return '--'
          } else {
            return cellValue == 1 ? '固定提成' : '比例提成'
          }
        },
      formatCommissionValue (row, column, cellValue, index) {
        if (cellValue == '' || +cellValue === 0) {
          return '--'
        } else {
          if (row.commissionWay == '1') {
            return cellValue + '元'
          } else {
            return cellValue + '%'
          }
        }
      },
      //数据初始化
      initData (actionPlanType, planType) {
        this.actionPlantype = actionPlanType
        this.plantype = planType
        this.selectedTab = '3'
        //判断门店经营类型如果没有经营范围都显示
        this.commissionRake = 3
        //   if (this.businessScope && this.businessScope.indexOf(0) != -1) {
        //     this.commissionRake = 3
        //   } else if (this.businessScope && this.businessScope.indexOf(1) != -1) {
        //     this.commissionRake = 4
        //   }
        this.getPersonAchievement()
        this.commodityBrand()
        this.commodityCategoryfun()
      },
      onChnageTab (tab, event) {
        this.initFilter()
        if (tab.name == '5') {
          this.getActiveGoodsList()
        } else {
          this.getPersonAchievement()
        }
      },
      //初始化筛选条件
      initFilter () {
        this.addGoodsForm.isCommission = ''
        this.addGoodsForm.commodityBrand = ''
        this.addGoodsForm.commodityCategory = ['']
        this.addGoodsForm.pageSize = 10
        this.addGoodsForm.pageNum = 1
        this.addGoodsForm.keyWords = ''
        this.addGoodsForm.activityTime = []
      },
      // --------------销售业绩 ----------------
      //添加产品弹框
      selectProduct () {
        if (this.actionPlantype == null) {
          this.$message.error('请确认选择您需要的门店提成方案')
          return
        }
        if (this.selectProductVisible) {
          this.activeProduct = JSON.parse(JSON.stringify(this.activeProductList))
        }
        this.selectProductVisible = !this.selectProductVisible
      },
      //删除区间
      deleRange (index) {
        this.sectionData.splice(index, 1)
        // this.$confirm('请确认是否删除该区间?', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   center: true
        // }).then(() => {
        //   deleRange(arr).then(res => {
        //     if (res.code == 200) {
        //       this.getPersonAchievement()
        //     }
        //   })
        // }).catch(() => {
        // })
      },
      //添加区间
      onAddSection () {
        if (this.sectionData.length >= 20) {
          this.$message.error('区间最多20条')
          return
        }
        this.sectionEdit = 1
        let newele = {
          amountMin: '',
          amountMax: '',
          commissionWay: 0,
          commissionValue: '',
          show: true
        }
        this.sectionData.push(newele)
      },
      //编辑区间
      openEdit () {
        if (this.actionPlantype == null) {
          this.$message.error('请确认选择您需要的门店提成方案')
          return
        }
        //选择提成产品提示
        // if (this.activeProductList.length == 0) {
        //   this.$message.error('请选择产品')
        //   return
        // }
        let arr = this.sectionData.map(function (item, index) {
          item.show = !item.show
          return item
        })
        this.sectionData = arr
        this.sectionEdit = 2
      },
      //  获取提成区间
      getPersonAchievement (defaultCommissionRake = '') {
        let num, size = ''
        if (defaultCommissionRake !== '') {
          this.commissionRake = defaultCommissionRake
          num = this.addGoodsForm.pageNum
          size = this.addGoodsForm.pageSize
        } else {
          this.commissionRake = this.selectedTab
          num = this.pageNum
          size = this.pageSize
        }
        //判断有执行方案
        let type = null
        if (this.actionPlantype == null) {
          type = this.plantype
        } else {
          type = this.actionPlantype
        }
        let data = {
          planType: type,
          commissionRake: this.commissionRake,
          pageNum: num,
          pageSize: size,
          shopId: this.shopId,
          name: this.addGoodsForm.keyWords,
          isCommission: this.addGoodsForm.isCommission,
          brandId: this.addGoodsForm.commodityBrand,
          primaryClassifyId: this.addGoodsForm.commodityCategory[this.addGoodsForm.commodityCategory.length - 1]
        }
        getCommercialTenant(data).then(res => {
          this.planId = res.data.id
          if (defaultCommissionRake !== '') {
            this.addGoodsForm.total = +res.data.pageTotal
          } else {
            this.total = +res.data.pageTotal
          }
          if (this.selectedTab === '3') {
            if (res.data.commissionDetailId) {
              this.commissionDetailId = res.data.commissionDetailId
            }
            //写死提成产品（商品、服务、次卡）
            let goodstype
            if (res.data.goodsType) {
              goodstype = res.data.goodsType.split(',')
            } else {
              goodstype = []
            }
            if (goodstype.length < this.productList.length) {
              this.commissionEdit()
            }
            // this.$set(this, 'activeProduct', goodstype)
            // this.activeProductList = goodstype

            if (res.data.commissionRange) {
              this.sectionData = res.data.commissionRange
              for (let i = 0; i < this.sectionData.length; i++) {
                this.sectionData[i].show = false
              }
            }
            this.alreadySectionData = JSON.parse(JSON.stringify(this.sectionData))
          } else if (this.selectedTab === '4') {
            this.serviceList = res.data.commissionDetail
          } else if (this.selectedTab === '5' && defaultCommissionRake == '0') {
            this.dialogGoodsList = res.data.commissionDetail
          }
        })
      },
      //修改提成
      commissionEdit () {
        if (this.selectedTab == '3') {
          let goodType = this.activeProduct.join(',')
          let arr = []
          let data = {
            commissionId: this.planId,
            commissionRake: this.commissionRake,
            id: this.commissionDetailId,
            goodsType: goodType,
            companyId: this.merchantId,
            shopId: this.shopId,
            source: this.soUrce,
          }
          arr.push(data)
          commissionDetail(arr).then(res => {
            if (res.code == 200) {
              //选择提成产品
              // this.activeProductList = this.activeProduct
              // this.selectProduct()
              this.offConfirm()
            }
          })
        } else {
          let arr = []
          let arrData = []
          let data = {
            commissionId: this.planId,
            commissionWay: this.dialogForm.commissionType,
            commissionValue: this.dialogForm.number,
            goodsId: '',
            commissionRake: this.commissionRake,
            goodsType: '',
            isCommission: this.dialogForm.isCommission,
            companyId: this.merchantId,
            shopId: this.shopId,
            source: this.soUrce,
          }
          if (this.dialogForm.activityTime.length > 0) {
            data.activityStart = util.getdatetime(this.dialogForm.activityTime[0])
            data.activityEnd = util.getdatetime(this.dialogForm.activityTime[1])
          }
          arrData = this.selectedList
          for (let i = 0; i < arrData.length; i++) {
            let newObj = {}
            if (arrData[i].goodsId || arrData[i].id || arrData[i].goodsShopId) {
              //添加商品
              if (this.addGoodsDialogFormVisible) {
                newObj = {
                  goodsId: arrData[i].goodsId,
                  id: ''
                }
              } else if (this.selectedTab == '5') {
                //活动期商品提成
                newObj = {
                  goodsId: arrData[i].goodsShopId,
                  id: arrData[i].id
                }
              } else {
                newObj = {
                  goodsId: arrData[i].goodsId,
                  id: arrData[i].id
                }
              }
              let obj = Object.assign({}, data, newObj)
              arr.push(obj)
            }
          }
          commissionDetail(arr).then(res => {
            if (res.code == 200) {
              if (this.innerVisible) {
                this.getActiveGoodsList()
              } else if (this.commissionRake == '5') {
                this.getActiveGoodsList()
              } else {
                this.getPersonAchievement()
              }
              this.dialogFormVisible = false
              this.innerVisible = false
              this.addGoodsDialogFormVisible = false
              this.offConfirm()
            }
          })
        }
      },
      //  保存提成区间
      onSaveCommissionSection () {
        let min = this.min
        let max = this.max
        let arr = JSON.parse(JSON.stringify(this.sectionData))
        //排序
        arr.sort(function (n1, n2) {
          return n1.amountMin - n2.amountMin
        })
        //遍历
        for (var i = 0; i < arr.length; i++) {
          let commissionWay = arr[0].commissionWay;
          if (arr.length >1) {
            if(commissionWay != arr[i].commissionWay) {
              this.$message.error('提成方式必须统一, 请检查后在提交')
              return false
            }
          }
          //区间的最小值不能大于等于区间最大值
          if (+arr[i].amountMin > +arr[i].amountMax) {
            this.$message.error('区间的最小值不能大于区间最大值')
            return false
          }
          //区间的最小值不能小于默认最小值
          if (+arr[i].amountMin < min) {
            this.$message.error('区间的最小值不能小于' + min)
            return false
          }

          //区间的最大值不能大于默认最大值
          if (+arr[i].amountMax > max) {
            this.$message.error('区间的最大值不能大于' + max)
            return false
          }
          //元素对比，从第二个元素开始
          if (i > 0) {
            //区间首尾是否相连
            if (+arr[i].amountMin !== +arr[i - 1].amountMax) {
              this.$message.error('区间必须连续')
              return false
            }
            //区间不能重叠
            if (+arr[i].amountMin < +arr[i - 1].amountMax) {
              this.$message.error('区间不能交叉重叠')
              return false
            }
          }
        }
        if (this.alreadySectionData.length != 0) {
          let deleData = this.alreadySectionData.map(function (item, index) {
            return item.id
          })
          deleRange(deleData).then(res => {
            if (res.code == 200) {
              if (this.sectionData.length > 0) {
                let addData = {
                  commissionId: this.planId,
                  ranges: this.sectionData
                }
                commissionRang(addData).then(res => {
                  if (res.code == 200) {
                    this.sectionEdit = null
                    this.getPersonAchievement()
                  }
                })
              } else {
                this.sectionEdit = null
                this.getPersonAchievement()
              }
            }
          })
        } else if (this.sectionData.length > 0) {  //没有区间时不必覆盖
          let addData = {
            commissionId: this.planId,
            ranges: this.sectionData
          }
          commissionRang(addData).then(res => {
            if (res.code == 200) {
              this.sectionEdit = null
              this.getPersonAchievement()
            }
          })
        } else {
          this.sectionEdit = null
        }

        // //新增区间
        // if (this.sectionEdit == '1') {
        //   let newArr = this.sectionData.splice(this.alreadySectionData.length)
        //   let data = {
        //     commissionId: this.planId,
        //     ranges: newArr
        //   }
        //   commissionRang(data).then(res => {
        //     if (res.code == 200) {
        //       this.sectionEdit = null
        //       this.getPersonAchievement()
        //     }
        //   })
        // } else {
        //   //编辑区间
        //   let arr = this.sectionData.map(function (item, index) {
        //     return {
        //       id: item.id,
        //       amountMin: item.amountMin,
        //       amountMax: item.amountMax,
        //       commissionWay: item.commissionWay,
        //       commissionValue: item.commissionValue
        //     }
        //   })
        //   updRange(arr).then(res => {
        //     if (res.code == 200) {
        //       this.sectionEdit = null
        //       this.getPersonAchievement()
        //     }
        //   })
        // }
      },
      onCancelCommissionSection () {
        this.sectionData = JSON.parse(JSON.stringify(this.alreadySectionData))
        this.sectionEdit = null
      },
      // --------------------------------------------------服务劳动弄提成
      onSelectionChange (val) {
        this.selectedList = val
      },
      //取消提成修改
      offConfirm () {
        this.dialogFormVisible = false
        this.innerVisible = false
        this.selectedList = []
        this.dialogForm.isCommission = 0
        this.dialogForm.commissionType = 1
        this.dialogForm.number = ''
        this.dialogForm.activityTime = []
      },
      // 确认修改
      onConfirmSet () {
        if (this.commissionRake == '5') {
          if (this.dialogForm.activityTime.length == 0) {
            this.$message.error('请选择活动时间')
            return
          }
          if (!this.dialogForm.number || this.dialogForm.number == 0) {
            this.$message.error('请输入提成值且大于0！')
            return
          }
        } else {
          if (this.dialogForm.isCommission == '0' && (!this.dialogForm.number || this.dialogForm.number == 0)) {
            this.$message.error('请输入提成值且大于0！')
            return
          }
        }
        this.commissionEdit()
      },
      onChangeServiceComm (type, commission = '', goodsId = '', id = '') {
        if (this.actionPlantype == null) {
          this.$message.error('请确认选择您需要的门店提成方案')
          return
        }
        // 0 单个修改服务劳动提成 1 批量修改
        if (commission == '5') {
          this.commissionRake = commission
        }
        if (this.commissionRake == '4') {
          this.diaLogTitle = '服务劳动提成'
        } else if (this.commissionRake == '5') {
          this.diaLogTitle = '活动期商品提成'
        }
        if (type === 0) {
          this.dialogFormVisible = true
          if (this.selectedTab == '5') {
            this.selectedList = new Array({
              goodsShopId: goodsId,
              id: id
            })
          } else {
            this.selectedList = new Array({
              goodsId: goodsId,
              id: id
            })
          }
        } else {
          if (this.selectedList.length > 0) {
            this.dialogFormVisible = true
          } else {
            if (this.commissionRake == '5') {
              this.$message.error('请选择需要操作的商品')
            } else if (this.commissionRake == '4') {
              this.$message.error('请选择需要操作的服务')
            }
          }
        }
      },

      // ---------------------------------------------------活动期商品提成
      //活动期时间
      selectedDateChange (val) {
        if (!val) {
          return
        }
        let arr1 = util.foryear(val[0])
        let today = util.foryear(new Date())
        let todayTime = util.fortime(new Date())
        let todayStr = (new Date()).getTime()
        let arr1Str = Date.parse(val[0])
        if (arr1 == today && arr1Str < todayStr) {
          let todayArr = today.split('-')
          let todayTimeArr = todayTime.split(':')
          val[0] = new Date(todayArr[0],todayArr[1]-1,todayArr[2],todayTimeArr[0],todayTimeArr[1])
        }
      },
      //添加商品
      addGoodsBtn () {
        if (this.actionPlantype == null) {
          this.$message.error('请确认选择您需要的门店提成方案')
          return
        }
        this.initFilter()
        this.getPersonAchievement(0)
        this.addGoodsDialogFormVisible = true
      },
      //获取活动期提成商品列表
      getActiveGoodsList () {
        let data = {
          commissionId: this.planId,
          shopId: this.shopId,
          pageSize: this.pageSize,
          pageNum: this.pageNum,
          commissionRake: 5,
          category: this.addGoodsForm.commodityCategory[this.addGoodsForm.commodityCategory.length - 1],
          brand: this.addGoodsForm.commodityBrand,
          isCommission: this.addGoodsForm.isCommission,
          name: this.addGoodsForm.keyWords
        }
        activeGoodsList(data).then(res => {
          this.activeGoodsList = res.data.goodsList
          this.total = res.data.pageTotal
        })
      },
      // 活动商品提成勾选
      onSelectionActiveChange (val) {
        this.selectedList = val
      },
      // 批量操作活动商品提成
      delActivityCommission (type, id = '') {
        if (this.actionPlantype == null) {
          this.$message.error('请确认选择您需要的门店提成方案')
          return
        }
        if (type == '0' && this.selectedList.length == 0) {
          this.$message.error('请选择要操作的商品')
          return
        }
        const h = this.$createElement
        this.$msgbox({
          title: '提示',
          message: h('div', null, [
            h('h4', null, '删除后将即时停止执行该商品的活动期提成，您确认要删除吗？'),
            h('p', null, '注：该商品在活动期已售卖/已过活动期的提成不受影响')
          ]),
          showCancelButton: true,
          confirmButtonText: '确认删除',
          cancelButtonText: '取 消',
          showClose: false,
          center: true,
          closeOnPressEscape: false,
          closeOnHashChange: false,
          closeOnClickModal: false
        }).then(() => {
          let arr = []
          if (type == '0') {
            arr = this.selectedList.map(function (item, index) {
              return item.id
            })
          } else {
            arr.push(id)
          }
          deleteCommission(arr).then(res => {
            if (res.code == 200) {
              this.getActiveGoodsList()
            }
          })
        }).catch(() => {
        })
      },
      // //删除活动期商品提成
      // delActivityCommission () {
      //   deleteCommission({ids: this.ids}).then(res => {
      //     if (res.data.code == 200) {
      //       this.getPersonAchievement()
      //     }
      //   })
      // },
      onChangeActiveComm (type, goodsId, id) {
        // 0 单个修改提成 1 批量修改
        if (type === 0) {
          this.selectedList = new Array({
            goodsId: goodsId,
            id: id
          })
        } else {
          if (this.selectedList.length == 0) {
            this.$message.error('请选择需要操作的商品')
            return
          }
        }
        this.commissionRake = 5
        this.innerVisible = true
        this.addGoodsDialogFormVisible = true
      },
      // 商品品牌
      commodityBrand () {
        selectByGoodsId({
          shopId: this.shopId,
          type: '0'
        }).then(res => {
          let a = {
            id: '',
            name: '全部'
          }
          res.data.list.unshift(a)
          this.commodityBrandList = res.data.list
        })
      },
      // 商品品类
      commodityCategoryfun () {
        getGoodsClassifyTreeList().then(res => {
          let a = {
            value: '',
            label: '全部'
          }
          res.data.unshift(a)
          this.commodityCategoryList = res.data
        })
      },
      // 勾选参加活动提成的商品
      onSelectionAddGoods (val) {
        this.selectedList = val
      },
      handleSizeChange (val, type = null) {
        this.pageSize = val
        this.pageNum = 1
        if (type == '5') {
          this.getActiveGoodsList()
        } else {
          this.getPersonAchievement()
        }
      },
      handleCurrentChange (val, type = null) {
        this.pageNum = val
        if (type == '5') {
          this.getActiveGoodsList()
        } else {
          this.getPersonAchievement()
        }
      },
      addGoodsHandleSizeChange (val, type) {
        this.addGoodsForm.pageSize = val
        this.addGoodsForm.pageNum = 1
        this.getPersonAchievement(0)
      },
      addGoodsHandleCurrentChange (val, type) {
        this.addGoodsForm.pageNum = val
        this.getPersonAchievement(0)
      },
      //数据格式化
      formatDate (value) {
        let result = ''
        if (value) {
          let arr1 = value.split(' ')[0]
          let arr2 = value.split(' ')[1].split(':')
          result = arr1 + ' ' + arr2[0] + ':' + arr2[1]
        } else {
          result = '--'
        }
        return result
      },
      formatIsCommission (row, column, cellValue, index) {
        if (row.commissionValue == '' || +row.commissionValue === 0) {
          return '否'
        } else {
          return '是'
        }
      },
    }
  }
</script>
<style scoped>
  .el-tabs {
    margin-bottom: 20px;
  }

  h5 {
    margin: 18px 0 0;
  }

  label {
    font-size: 14px;
  }

  .el-table {
    margin: 10px 0;
  }

  .p-tip {
    border-bottom: 1px solid #dfdfdf;
    margin: 10px 0;
    padding-bottom: 10px;
  }

  .p-tip span {
    display: inline-block;
    color: #fb4044;
    margin: 0 50px 0 15px;
    font-size: 12px;
  }


  .set-active-comm {
    margin-top: 20px;
  }

  .goods-add-dialog .el-dialog {
    width: 88%;
  }

  .add-new-section {
    text-align: center;
    width: 60%;
  }

  .checkbox-block {
    display: block;
    margin-top: 20px;
    margin-left: 40px;
  }

  .mark {
    font-size: 14px;
    color: #f56c6c;
    margin-left: 40px;
    margin-top: 20px;
  }

  .hasTips {
    font-size: 14px;
    color: #606266;
    margin-left: 20px;
  }

  .section-edit-btns {
    border-top: 1px dashed #DCDFE6;
    margin-top: 20px;
  }

  .from-filter {
    margin: 18px 0 0 20px;
    color: #606266;
    font-size: 14px;
  }
  .tips{
    color: #fb4044;
    font-size: 14px;
    margin-left: 20px;
  }
</style>
<style>
  .goods-add-dialog .el-dialog {
    width: 88%;
  }
</style>
